package com.example.backend.controller;

import com.example.backend.common.api.R;
import com.example.backend.dto.LoginDTO;
import com.example.backend.dto.RegisterDTO;
import com.example.backend.service.AuthService;
import com.example.backend.common.validator.RegisterValidator;
import com.example.backend.common.api.ResultCode;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Validated
public class AuthController {
    
    private final AuthService authService;
    private final RegisterValidator registerValidator;
    
    /**
     * 登录
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody @Valid LoginDTO loginDTO) {
        String token = authService.login(loginDTO.getUsername(), loginDTO.getPassword());
        return R.ok(token);
    }
    
    /**
     * 刷新Token
     */
    @PostMapping("/refresh")
    public R<String> refresh() {
        String newToken = authService.refreshToken();
        return R.ok(newToken);
    }
    
    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public R<Void> logout() {
        authService.logout();
        return R.ok();
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public R<Void> register(@RequestBody @Valid RegisterDTO registerDTO) {
        // 参数校验
        registerValidator.validate(registerDTO);
        
        // 注册用户
        return authService.register(registerDTO) ? 
                R.ok() : R.fail(ResultCode.REGISTER_FAIL);
    }
} 